package com.qf.web.filter;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //实现自动登录

    /**
     * 0. 验证是否登录了， 如果没有登录，则自动登录； 如果登录成功了，放行
     * 1. 从cookie获取用户信息，解密
     * 2. 验证码用户名，密码是否正确
     * 3. 如果正确，登录成功
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) servletResponse;
        //从session获取用户信息
        Object user = request.getSession().getAttribute("user");
        //如果已经登录了， 则放行
        if(user != null) {
            filterChain.doFilter(request, response);
            return;
        }

        //自动登录
        //获取cookie
        Cookie[] cookies = request.getCookies();
        if(cookies == null  || cookies.length == 0) {
            response.sendRedirect("/login.jsp");
            filterChain.doFilter(request, response);
            return;
        }

        //循环cookie
        for (javax.servlet.http.Cookie cookie : cookies) {
            String name = cookie.getName();
            //查找 需要的用户信息
            if("userinfo-2202".equals(name)) {
                String value = cookie.getValue();
                //解密 : admin#123456
                String userInfo = Base64Utils.decode(value);
                String[] arr = userInfo.split("#");
                if(arr != null  && arr.length == 2) {
                    UserService userService = new UserServiceImpl();
                    User login = userService.login(arr[0], arr[1]);
                    if(login != null) {
                        request.getSession().setAttribute("user", login);
                        break;
                    }

                }

            }
        }

        //最后放行
        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }
}
